Skip to content

fix(libSceFont): stop a font writing from owning its string's characters - #11521

Merged
oneandonlydean merged 1 commit into
boykopovar:mainfrom
Lindamea1:fix/font-writing-non-owning
Oct 28, 2026
Merged

oneandonlydean merged 1 commit into
boykopovar:mainfrom
Lindamea1:fix/font-writing-non-owning

Conversation

@Lindamea1

@Lindamea1 Lindamea1 commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

What

On main, sceFontWritingInit makes the caller's SceFontWriting own a reference to the string's host CharacterStorage (Text.cpp:649-650: refCount.fetch_add, ownsStorage = true). Only the next sceFontWritingInit on the same, unchanged bytes gives it back, by reading the writing's previous contents (Text.cpp:643). sceFontDestroyString drops only the string's own reference.

A SceFontWriting is 256 bytes of caller memory (FontTypes.hpp:328-330), and none of the five writing exports (Api.hpp:254-258) tears one down. A guest may zero, overwrite or copy it. On main this means:

  • Each string drawn with a fresh, zeroed or overwritten writing leaks its CharacterStorage (32 bytes, Text.cpp:331) and its characters (200 bytes each, Text.cpp:345). The existing guest_font test leaks this way, and LeakSanitizer reports it.
  • A copied writing returns the reference twice. Re-initialising both copies after the string is destroyed decrements freed memory (Text.cpp:92). In a Release build, doing this twice makes glibc abort with malloc(): unaligned tcache chunk detected.

With this change, a string's characters live in the string's FontMemory, and a writing only points at its string:

  • sceFontCreateString collects the characters in a temporary vector, then allocates them through the string's FontMemory, as it already allocated the string itself, and copies and links them there. CharacterStorage and its reference count are gone, so the character pointers the guest receives, from sceFontStringRefersTextCharacters, from sceFontWritingRefersRenderStepCharacter and through the characters' links, point into memory from the guest's own allocator. If that allocation fails, the string is released and the call returns SCE_FONT_ERROR_ALLOCATION_FAILED, as when the string's own allocation fails.
  • sceFontDestroyString clears the string's magic, then frees the characters and the string through the interface, as DestroyWords does with its nodes (Words.cpp:270-280). A sceFontCreateString that fails also clears the magic before it releases the string, so no string block this library frees keeps it.
  • A writing keeps only the pointer to its string, and sceFontWritingInit no longer reads the writing's previous bytes. sceFontWritingRefersRenderStep and sceFontWritingRefersRenderStepCharacter check the string's magic before they read the string, so they return null once it is destroyed, with the exception under Behaviour change.
  • The two error returns after the writing is reset (a character outside the string, a first step that fails) clear the string pointer, so such a writing steps nothing. The two earlier returns (a null argument, an invalid string) leave the writing as it was. All four behave as on main.

Behaviour change, after sceFontDestroyString:

  • On main a writing keeps stepping, because it holds a reference, and character pointers taken from the string stay valid while one does. With this change, both step calls return null, on the writing and on any copy of it, unless the destroyed string's memory holds the string magic again; then they read that memory as a string. A string created between the destroy and the step is likely to land there: sceFontDestroyString frees the string's block last, and an allocator that hands out the most recently freed block of a size class first, as the guest heap does (GuestHeap.cpp:84-113), is likely to give that block to the next string. Character pointers taken from the string point into the freed characters. Because the string and its characters come from the guest's allocator, the library no longer frees host memory that a writing or a character pointer refers to.
  • A second sceFontDestroyString through another copy of the handle returns SCE_FONT_ERROR_INVALID_STRING instead of freeing the string again, with the same exception, in which case it frees that memory as a string.
  • What the console returns in these cases, and where it allocates the characters, is not measured. A new Functional entry in docs/dev/debt/libSceFont.md says so.

Reference. libSceFont is a Sony library, so FreeBSD has no counterpart:

Callers, both PS1 Classics:

Neither discussion reports memory growth. The only stop reported, in #9516, is the documented missing-system-fonts case. #3839 reports its title playable, and #9516, with the system fonts and #5209, reaches the first mission. I ran neither title. How often they draw, whether they reuse their writing, and whether they step a writing after destroying its string, is not measured.

Overlap: #5209 changes FillWritingMetricsFromGlyph in Text.cpp. A three-way merge of its head (6912742) with this branch merges Text.cpp cleanly, and the merged file passes g++ -fsyntax-only with the build's flags. #5209 already conflicts with main in docs/dev/debt/libSceFont.md, with or without this branch. The overlap bot also lists #8250 (18e0b85), which changes only docs/dev/debt/libSceFont.md. It already conflicts with main there, near the top of the file, and merged with this branch it conflicts in the same place, away from this entry. #11618 and #11707 add checks to GuestFont.cpp; each merges cleanly with this branch.

Regression tests, in guest_font (core/libs/tests/GuestFont.cpp):

  • CheckWritingDoesNotOwnCharacters draws a 32-character string 512 times, each time with a fresh writing, and checks the step count. The memory interface's allocation count must come back to where it was, and with glibc mallinfo2().uordblks must grow by less than 256 KiB. It copies an initialised writing and steps both copies, destroys the string, and re-initialises and steps both copies on a new string. It re-initialises a writing with a character of another string, expects SCE_FONT_ERROR_INVALID_PARAMETER, and checks that the writing then steps nothing.
  • CheckWritingAfterStringDestroyed uses its own FontMemory, whose release marks the block as released but keeps it allocated, so that reading a released block stays inside memory the test owns, as reading freed guest memory would in a title. It checks:
    • a characters allocation that fails returns SCE_FONT_ERROR_ALLOCATION_FAILED and releases the string, and sceFontDestroyString on a handle to that released block returns SCE_FONT_ERROR_INVALID_STRING without a second release;
    • the string and all 32 characters are in blocks from this interface;
    • a writing is stepped twice and copied byte for byte; after sceFontDestroyString the string's and the characters' blocks have been released through the interface, and on the writing and on the copy sceFontWritingRefersRenderStepCharacter returns null and sets the letter step to null, and sceFontWritingRefersRenderStep returns null;
    • re-initialising the copy with the destroyed handle returns SCE_FONT_ERROR_INVALID_STRING, and the copy still steps nothing;
    • a second destroy through another copy of the handle returns SCE_FONT_ERROR_INVALID_STRING without a second release;
    • the writing, re-initialised at a new string's second character, and the copy, at its first, step it to its end (31 and 32 steps), and the writing's last step character is the new string's last;
    • at the end, every block has been released exactly once.

Tested

Gentoo Linux, kernel 7.2.8, GCC 16.2.1, AMD Ryzen 7 9800X3D, Release, BUILD_TESTING=ON, on main 8df2c3e.

  • ctest --test-dir build -R '^guest_font$' passes. Controls, each with only Text.cpp changed and rebuilt:
    • main's Text.cpp: aborts with Font check failed at line 179, the heap check.
    • the Text.cpp of this PR's previous head (798a929): aborts at line 231, because no characters are allocated through the memory interface.
    • this change without the magic clear in sceFontDestroyString: aborts at line 249, because the writing still returns its step character after the destroy.
    • this change without the magic clear on a failed sceFontCreateString: aborts at line 74, where the test's release finds the failed create's block released a second time.
    • this change without writing->string = nullptr; on the out-of-range return: aborts at line 197, the failed-init check.
  • AddressSanitizer and LeakSanitizer: in a local -DANYPS5_ENABLE_ASAN=ON Release tree, guest_font_tests and the libraries it links (libSceFont, libSceFontFt, libc, libkernel) were rebuilt at this head. ASAN_OPTIONS=detect_leaks=1 ctest --test-dir build-asan -R '^guest_font$' passes with no report. With main's Text.cpp and GuestFont.cpp it fails with LeakSanitizer's report of a direct leak of 32 bytes at Text.cpp:331 and an indirect leak of 400 bytes at Text.cpp:345, both from GuestFont.cpp:658.
  • Heap growth, measured with a probe outside the repository (probe_writing.cpp, attached below). It runs the same create, init, step and destroy cycle as the test against the Release libraries, after one warm-up draw. Unlike the test, it draws an alternating AVAV... string in a minimal font without a kern table, at 32 px, with a new text source for each draw. For 512 draws of a 32-character string:
    • a fresh zeroed writing each time: main grows by 3,309,568 bytes and leaves 1,024 host allocations live; this change grows by 0 bytes and leaves none;
    • one writing reused: main grows by 6,512 bytes; this change by 0;
    • one writing filled with 0xA5 between draws, as a reused stack slot would be: main grows by 3,309,568 bytes; this change by 0.
    • In all three, the probe's memory interface ends with the same 50 live blocks on main and with this change.
  • The same probe:
    • The copy pattern, run twice, aborts on main with malloc(): unaligned tcache chunk detected (exit 134). With this change it runs 100 times.
    • Init with a character of another string returns 0x80460002, and the writing then steps 0 times, both on main and with this change.
    • A writing stepped after its string is destroyed steps 31 more times on main and 0 times with this change. The probe's release calls free, so with this change that read is of freed malloc memory; CheckWritingAfterStringDestroyed uses its own release so that this case reads only memory the test still owns.
  • probe_after_destroy.cpp (attached below) steps a writing, or asks for its step character, after destroying its string. Built against the ASan tree: on main it steps 31 more times, or gets a non-null character, and ASan reports no use-after-free. With this change, ASan reports a heap-use-after-free READ of size 2 in GetStringData (Text.cpp:73), called from either step call: the read of the destroyed string's magic, in the block that the probe's own Allocate returned to sceFontCreateString and its Release freed in sceFontDestroyString. The probe's release calls free, so ASan sees that freed guest-allocator block.
  • tools/select_tests.py picked 458 of the 2506 tests for this change. All pass, none skipped.
  • Windows: Text.cpp and GuestFont.cpp compile without warnings with x86_64-w64-mingw32-g++ 16.2.0 (-std=gnu++20 -fsyntax-only -Wall -Wextra). This is a syntax check, not a Windows build or run. The heap check compiles out there.
  • Host g++ -std=gnu++20 -fsyntax-only -Wall -Wextra on both files: no warnings.
  • tools/check_compile.py, tools/check_test_registration.py and tools/check_conventions.py pass.
  • Rebased onto main 5bc8403 before this push (256 commits, none in these three files). There guest_font passes in the Release tree, and in the ASan tree with detect_leaks=1 and no report; tools/select_tests.py picks 465 of the 2536 tests, all passing; and the overlap checks above give the same results.

Not tested: no Windows or macOS build or run, no console, and I ran neither PPSA06699 nor PPSA06323.

Probe sources and output

probe_writing.cpp is built from the repository root against the Release tree:

L=$PWD/build/core/libs/libs/unpatched
c++ -std=gnu++20 -g -O1 -I core/libs probe_writing.cpp -o probe_writing -Wl,--no-as-needed -pie -Wl,-rpath,$L \
  $L/libSceFont.prx $L/libSceFontFt.prx $L/libc.prx $L/libkernel.prx
// Usage: probe_writing MODE N LEN (N draws of a LEN-character string; copy, badinit and stepafter ignore N)
//   zeroed    fresh zero-initialised FontWriting per draw (create string, init, step to end, destroy string)
//   reuse     one FontWriting object reused for every draw
//   scribble  one FontWriting reused, overwritten with 0xA5 after each draw (stack slot reused by other calls)
//   copy      copy an initialised writing, destroy its string, re-init both copies on a new string
//   copyloop  the copy pattern N times, with a small allocation in between unless PROBE_NO_EXTRA is set
//   badinit   init a writing with a character of another string, then step it
//   stepafter init a writing, step once, destroy its string, then keep stepping the writing
#include "prx/libSceFontFt/include/Api.hpp"
#include "prx/libSceFont/include/Api.hpp"
#include "prx/libc/include/General.hpp"
#include "tests/FontFixture.hpp"
#include <atomic>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <new>
#include <string>
#include <vector>
#include <malloc.h>
#include <unistd.h>

#if defined(__SANITIZE_ADDRESS__)
#define PROBE_ASAN 1
#else
#define PROBE_ASAN 0
#endif

#if !PROBE_ASAN
// Count host operator new/delete calls made by every module (the PIE exports these, so libSceFont binds to them).
static std::atomic<long> liveNews{0};
static std::atomic<long> totalNews{0};
void* operator new(std::size_t size) {
    ++liveNews;
    ++totalNews;
    if (void* p = std::malloc(size ? size : 1)) return p;
    throw std::bad_alloc();
}
void operator delete(void* p) noexcept {
    if (p) --liveNews;
    std::free(p);
}
void operator delete(void* p, std::size_t) noexcept {
    if (p) --liveNews;
    std::free(p);
}
#endif

static void Check(bool value, int line) {
    if (!value) {
        std::fprintf(stderr, "probe check failed at line %d\n", line);
        std::abort();
    }
}
#define Require(value) Check((value), __LINE__)

static long guestAllocs = 0;
static void* APS5_VABI Allocate(void*, std::uint32_t size) { ++guestAllocs; return std::malloc(size); }
static void APS5_VABI Release(void*, void* pointer) { if (pointer) --guestAllocs; std::free(pointer); }

struct Parsed { const char* text; std::size_t at; FontHandle font; };
static std::int32_t APS5_VABI Parse(FontTextSource* source, void** order, FontTextParseResult* result) {
    auto* parsed = static_cast<Parsed*>(source->textObject);
    *order = const_cast<char*>(parsed->text + parsed->at);
    if (parsed->text[parsed->at] == 0) { result->Terminate.terminateCode = 0; return 0; }
    result->FontCode.font = parsed->font;
    result->FontCode.code = static_cast<unsigned char>(parsed->text[parsed->at++]);
    return 1;
}

static FontMemory memory{};
static FontHandle font = nullptr;

static FontString MakeString(const std::string& text, Parsed& parsed, FontTextSource& source, FontTextCharacter** first) {
    parsed = Parsed{text.c_str(), 0, font};
    source = FontTextSource{};
    Require(sceFontTextSourceInit(&source, parsed.text, static_cast<std::uint32_t>(text.size()), Parse, &parsed) == SCE_FONT_OK);
    FontString string = nullptr;
    Require(sceFontCreateString(&memory, &source, nullptr, &string) == SCE_FONT_OK && string != nullptr);
    std::uint32_t count = 0;
    *first = sceFontStringRefersTextCharacters(string, &count);
    Require(*first != nullptr && count == text.size());
    return string;
}

static long Steps(FontWriting* writing) {
    long steps = 0;
    while (sceFontWritingRefersRenderStep(writing) != nullptr) ++steps;
    return steps;
}

static long long HeapInUse() { return static_cast<long long>(mallinfo2().uordblks); }

int main(int argc, char** argv) {
    const std::string mode = argc > 1 ? argv[1] : "zeroed";
    const long iterations = argc > 2 ? std::atol(argv[2]) : 100;
    const std::size_t length = argc > 3 ? static_cast<std::size_t>(std::atol(argv[3])) : 16;
    const std::filesystem::path fontRoot = std::filesystem::path(argv[0]).parent_path() / ("fonts-" + std::to_string(::getpid()));
    std::filesystem::create_directories(fontRoot);
    ::setenv("ANYPS5_SYSTEM_FONTS", fontRoot.c_str(), 1);

    const FontMemoryInterface iface{Allocate, Release, nullptr, nullptr, nullptr, nullptr};
    Require(sceFontMemoryInit(&memory, nullptr, 0, &iface, nullptr, nullptr, nullptr) == SCE_FONT_OK);
    FontLibrary library = nullptr;
    Require(sceFontCreateLibrary(&memory, sceFontSelectLibraryFt(0), &library) == SCE_FONT_OK);
    Require(sceFontSupportExternalFonts(library, 4, 0x52) == SCE_FONT_OK);
    const auto data = FontFixture::BuildFont(3, {
        {"cmap", FontFixture::Words({0, 1, 3, 1, 0, 12, 4, 40, 0, 6, 4, 1, 2, 'A', 'V', 0xFFFF, 0, 'A', 'V', 0xFFFF, 1 - 'A', 2 - 'V', 1, 0, 0, 0})},
    });
    Require(sceFontOpenFontMemory(library, data.data(), static_cast<std::uint32_t>(data.size()), nullptr, &font) == SCE_FONT_OK && font);
    Require(sceFontSetScalePixel(font, 32.0f, 32.0f) == SCE_FONT_OK);

    std::string text;
    for (std::size_t i = 0; i < length; ++i) text.push_back(i % 2 ? 'V' : 'A');

    if (mode == "zeroed" || mode == "reuse" || mode == "scribble") {
        // Warm up once so lazily created library state does not count.
        {
            Parsed p{}; FontTextSource s{}; FontTextCharacter* first = nullptr;
            FontString string = MakeString(text, p, s, &first);
            FontWriting w{};
            Require(sceFontWritingInit(&w, string, first) == SCE_FONT_OK);
            Steps(&w);
            Require(sceFontDestroyString(&string) == SCE_FONT_OK);
        }
        const long long heapBefore = HeapInUse();
#if !PROBE_ASAN
        const long newsBefore = liveNews.load();
#endif
        FontWriting reused{};
        long steps = 0;
        for (long i = 0; i < iterations; ++i) {
            Parsed p{}; FontTextSource s{}; FontTextCharacter* first = nullptr;
            FontString string = MakeString(text, p, s, &first);
            FontWriting fresh{};
            FontWriting* w = mode == "zeroed" ? &fresh : &reused;
            Require(sceFontWritingInit(w, string, first) == SCE_FONT_OK);
            steps += Steps(w);
            Require(sceFontDestroyString(&string) == SCE_FONT_OK && string == nullptr);
            if (mode == "scribble") std::memset(&reused, 0xA5, sizeof reused);
        }
        const long long heapAfter = HeapInUse();
        std::printf("mode=%s iterations=%ld length=%zu steps=%ld heap_in_use_growth=%lld bytes (%.1f per draw) guest_allocs_outstanding=%ld",
                    mode.c_str(), iterations, length, steps, heapAfter - heapBefore,
                    static_cast<double>(heapAfter - heapBefore) / static_cast<double>(iterations ? iterations : 1), guestAllocs);
#if !PROBE_ASAN
        std::printf(" host_new_outstanding_growth=%ld", liveNews.load() - newsBefore);
#endif
        std::printf("\n");
    } else if (mode == "copy") {
        Parsed p1{}; FontTextSource s1{}; FontTextCharacter* first1 = nullptr;
        FontString string1 = MakeString(text, p1, s1, &first1);
        FontWriting a{};
        Require(sceFontWritingInit(&a, string1, first1) == SCE_FONT_OK);
        FontWriting b;
        std::memcpy(&b, &a, sizeof a); // a struct copy, e.g. saving the writing state
        std::printf("a steps=%ld b steps=%ld\n", Steps(&a), Steps(&b));
        Require(sceFontDestroyString(&string1) == SCE_FONT_OK);
        Parsed p2{}; FontTextSource s2{}; FontTextCharacter* first2 = nullptr;
        FontString string2 = MakeString(text, p2, s2, &first2);
        std::printf("re-init a\n");
        std::fflush(stdout);
        Require(sceFontWritingInit(&a, string2, first2) == SCE_FONT_OK);
        std::printf("re-init b\n");
        std::fflush(stdout);
        Require(sceFontWritingInit(&b, string2, first2) == SCE_FONT_OK);
        std::printf("copy pattern done: a steps=%ld b steps=%ld\n", Steps(&a), Steps(&b));
        Require(sceFontDestroyString(&string2) == SCE_FONT_OK);
    } else if (mode == "copyloop") {
        std::vector<void*> keep;
        for (long i = 0; i < iterations; ++i) {
            Parsed p1{}; FontTextSource s1{}; FontTextCharacter* first1 = nullptr;
            FontString string1 = MakeString(text, p1, s1, &first1);
            FontWriting a{};
            Require(sceFontWritingInit(&a, string1, first1) == SCE_FONT_OK);
            FontWriting b;
            std::memcpy(&b, &a, sizeof a);
            Steps(&a);
            Require(sceFontDestroyString(&string1) == SCE_FONT_OK);
            Parsed p2{}; FontTextSource s2{}; FontTextCharacter* first2 = nullptr;
            FontString string2 = MakeString(text, p2, s2, &first2);
            Require(sceFontWritingInit(&a, string2, first2) == SCE_FONT_OK); // frees string1's storage
            if (!std::getenv("PROBE_NO_EXTRA")) keep.push_back(new char[24]);
            Require(sceFontWritingInit(&b, string2, first2) == SCE_FONT_OK); // decrements freed (or reused) memory
            Require(sceFontWritingInit(&a, string2, first2) == SCE_FONT_OK);
            Require(sceFontDestroyString(&string2) == SCE_FONT_OK);
        }
        std::printf("copyloop iterations=%ld survived\n", iterations);
        for (void* p : keep) delete[] static_cast<char*>(p);
    } else if (mode == "badinit") {
        Parsed p1{}; FontTextSource s1{}; FontTextCharacter* first1 = nullptr;
        FontString string1 = MakeString(text, p1, s1, &first1);
        Parsed p2{}; FontTextSource s2{}; FontTextCharacter* first2 = nullptr;
        FontString string2 = MakeString(text, p2, s2, &first2);
        FontWriting a{};
        const int rc = sceFontWritingInit(&a, string1, first2); // a character of another string
        std::printf("init with a foreign character: rc=%#x, steps afterwards=%ld\n", static_cast<unsigned>(rc), Steps(&a));
        Require(sceFontDestroyString(&string2) == SCE_FONT_OK);
        Require(sceFontDestroyString(&string1) == SCE_FONT_OK);
    } else if (mode == "stepafter") {
        Parsed p1{}; FontTextSource s1{}; FontTextCharacter* first1 = nullptr;
        FontString string1 = MakeString(text, p1, s1, &first1);
        FontWriting a{};
        Require(sceFontWritingInit(&a, string1, first1) == SCE_FONT_OK);
        Require(sceFontWritingRefersRenderStep(&a) != nullptr);
        Require(sceFontDestroyString(&string1) == SCE_FONT_OK);
        std::printf("steps after the string was destroyed: %ld\n", Steps(&a));
    }

    Require(sceFontCloseFont(font) == SCE_FONT_OK);
    Require(sceFontDestroyLibrary(&library) == SCE_FONT_OK);
    Require(sceFontMemoryTerm(&memory) == SCE_FONT_OK);
    std::filesystem::remove_all(fontRoot);
    return 0;
}

Output, without the libraries' log lines. On main:

$ ./probe_writing zeroed 512 32
mode=zeroed iterations=512 length=32 steps=16384 heap_in_use_growth=3309568 bytes (6464.0 per draw) guest_allocs_outstanding=50 host_new_outstanding_growth=1024
$ ./probe_writing reuse 512 32
mode=reuse iterations=512 length=32 steps=16384 heap_in_use_growth=6512 bytes (12.7 per draw) guest_allocs_outstanding=50 host_new_outstanding_growth=2
$ ./probe_writing scribble 512 32
mode=scribble iterations=512 length=32 steps=16384 heap_in_use_growth=3309568 bytes (6464.0 per draw) guest_allocs_outstanding=50 host_new_outstanding_growth=1024
$ ./probe_writing badinit 1 32
init with a foreign character: rc=0x80460002, steps afterwards=0
$ ./probe_writing stepafter 1 32
steps after the string was destroyed: 31
$ PROBE_NO_EXTRA=1 ./probe_writing copyloop 2 32
malloc(): unaligned tcache chunk detected
(exit status 134)

With this change:

$ ./probe_writing zeroed 512 32
mode=zeroed iterations=512 length=32 steps=16384 heap_in_use_growth=0 bytes (0.0 per draw) guest_allocs_outstanding=50 host_new_outstanding_growth=0
$ ./probe_writing reuse 512 32
mode=reuse iterations=512 length=32 steps=16384 heap_in_use_growth=0 bytes (0.0 per draw) guest_allocs_outstanding=50 host_new_outstanding_growth=0
$ ./probe_writing scribble 512 32
mode=scribble iterations=512 length=32 steps=16384 heap_in_use_growth=0 bytes (0.0 per draw) guest_allocs_outstanding=50 host_new_outstanding_growth=0
$ ./probe_writing badinit 1 32
init with a foreign character: rc=0x80460002, steps afterwards=0
$ ./probe_writing stepafter 1 32
steps after the string was destroyed: 0
$ ./probe_writing copy 1 32
a steps=32 b steps=32
re-init a
re-init b
copy pattern done: a steps=32 b steps=32
$ PROBE_NO_EXTRA=1 ./probe_writing copyloop 100 32
copyloop iterations=100 survived

probe_after_destroy.cpp is built the same way against the ASan tree, with -fsanitize=address -fno-omit-frame-pointer added, and run with that tree's libSceFont.prx built from main's Text.cpp and from this change's. Its argument is step, or anything else to ask for the step's character:

#include "prx/libSceFontFt/include/Api.hpp"
#include "prx/libSceFont/include/Api.hpp"
#include "prx/libc/include/General.hpp"
#include "tests/FontFixture.hpp"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <string>
#include <unistd.h>

static void Check(bool value, int line) {
    if (!value) {
        std::fprintf(stderr, "probe check failed at line %d\n", line);
        std::abort();
    }
}
#define Require(value) Check((value), __LINE__)

static void* APS5_VABI Allocate(void*, std::uint32_t size) { return std::malloc(size); }
static void APS5_VABI Release(void*, void* pointer) { std::free(pointer); }

struct Parsed {
    const char* text;
    std::size_t at;
    FontHandle font;
};

static std::int32_t APS5_VABI Parse(FontTextSource* source, void** order, FontTextParseResult* result) {
    auto* parsed = static_cast<Parsed*>(source->textObject);
    *order = const_cast<char*>(parsed->text + parsed->at);
    if (parsed->text[parsed->at] == 0) {
        result->Terminate.terminateCode = 0;
        return 0;
    }
    result->FontCode.font = parsed->font;
    result->FontCode.code = static_cast<unsigned char>(parsed->text[parsed->at++]);
    return 1;
}

int main(int argc, char** argv) {
    const std::string mode = argc > 1 ? argv[1] : "step";
    const std::filesystem::path fontRoot = std::filesystem::path(argv[0]).parent_path() / ("fonts-" + std::to_string(::getpid()));
    std::filesystem::create_directories(fontRoot);
    ::setenv("ANYPS5_SYSTEM_FONTS", fontRoot.c_str(), 1);
    const FontMemoryInterface iface{Allocate, Release, nullptr, nullptr, nullptr, nullptr};
    FontMemory memory{};
    Require(sceFontMemoryInit(&memory, nullptr, 0, &iface, nullptr, nullptr, nullptr) == SCE_FONT_OK);
    FontLibrary library = nullptr;
    Require(sceFontCreateLibrary(&memory, sceFontSelectLibraryFt(0), &library) == SCE_FONT_OK);
    Require(sceFontSupportExternalFonts(library, 4, 0x52) == SCE_FONT_OK);
    const auto data = FontFixture::BuildFont(3, {
        {"cmap", FontFixture::Words({0, 1, 3, 1, 0, 12, 4, 40, 0, 6, 4, 1, 2, 'A', 'V', 0xFFFF, 0, 'A', 'V', 0xFFFF, 1 - 'A', 2 - 'V', 1, 0, 0, 0})},
    });
    FontHandle font = nullptr;
    Require(sceFontOpenFontMemory(library, data.data(), static_cast<std::uint32_t>(data.size()), nullptr, &font) == SCE_FONT_OK && font);
    Require(sceFontSetScalePixel(font, 32.0f, 32.0f) == SCE_FONT_OK);
    const std::string text(32, 'A');
    Parsed parsed{text.c_str(), 0, font};
    FontTextSource source{};
    Require(sceFontTextSourceInit(&source, parsed.text, static_cast<std::uint32_t>(text.size()), Parse, &parsed) == SCE_FONT_OK);
    FontString string = nullptr;
    Require(sceFontCreateString(&memory, &source, nullptr, &string) == SCE_FONT_OK);
    std::uint32_t count = 0;
    FontTextCharacter* characters = sceFontStringRefersTextCharacters(string, &count);
    Require(characters != nullptr && count == text.size());
    FontWriting writing{};
    Require(sceFontWritingInit(&writing, string, characters) == SCE_FONT_OK);
    Require(sceFontWritingRefersRenderStep(&writing) != nullptr);
    Require(sceFontDestroyString(&string) == SCE_FONT_OK);
    std::printf("string destroyed, mode=%s\n", mode.c_str());
    std::fflush(stdout);
    if (mode == "step") {
        long steps = 0;
        while (sceFontWritingRefersRenderStep(&writing) != nullptr) ++steps;
        std::printf("steps after destroy: %ld\n", steps);
    } else {
        const FontWritingLetterStep* letter = nullptr;
        FontTextCharacter* character = sceFontWritingRefersRenderStepCharacter(&writing, &letter);
        std::printf("character after destroy: %s\n", character ? "non-null" : "null");
    }
    Require(sceFontCloseFont(font) == SCE_FONT_OK);
    Require(sceFontDestroyLibrary(&library) == SCE_FONT_OK);
    Require(sceFontMemoryTerm(&memory) == SCE_FONT_OK);
    std::filesystem::remove_all(fontRoot);
    return 0;
}

On main the runs used ASAN_OPTIONS=detect_leaks=0; with leak detection on, LeakSanitizer reports the string's leaked storage at exit.

main, step:              steps after destroy: 31
main, character:         character after destroy: non-null
this change, step:       ERROR: AddressSanitizer: heap-use-after-free ... READ of size 2
                             #0 GetStringData core/libs/prx/libSceFont/src/Text.cpp:73
                             #1 PopulateWritingStep core/libs/prx/libSceFont/src/Text.cpp:177
                             #2 sceFontWritingRefersRenderStep core/libs/prx/libSceFont/src/Text.cpp:668
this change, character:  ERROR: AddressSanitizer: heap-use-after-free ... READ of size 2
                             #0 GetStringData core/libs/prx/libSceFont/src/Text.cpp:73
                             #1 sceFontWritingRefersRenderStepCharacter core/libs/prx/libSceFont/src/Text.cpp:681
both, with this change:  freed by Release (probe_after_destroy.cpp:21) from sceFontDestroyString (Text.cpp:369),
                         previously allocated by Allocate (probe_after_destroy.cpp:20) from sceFontCreateString (Text.cpp:306)

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes

🤖 Generated with Claude Code

@MarcZX10 MarcZX10 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The change removes ownership tied to opaque caller memory, which currently leaks each CharacterStorage when a caller initializes a fresh SceFontWriting; the new test exercises repeated fresh writings, copied writing state and failed initialization. The second error path now clears storage, preventing a failed writing from stepping stale state. The PR reports the focused guest_font test passing on the change and failing on main at the intended leak/copy checks, plus an ASan comparison showing the main-branch leak and copied-writing use-after-free.

There is an explicit lifetime caveat: after sceFontDestroyString, the writing's character storage is freed, so stepping that writing or using a previously returned character pointer is a host use-after-free. I found no evidence in this review that titles do so, and the PR records that PS5 behavior and title call order are unmeasured. The PS4 measurement and Kyty reference support storing writing state in caller memory and treating it as non-owning; this approval does not claim PS5 confirmation. Conventions, diff checks, eligibility, intake and labels pass; hosted product and sanitizer jobs are skipped. I could not run the guest_font target in my local relinker-only scratch build.

@github-actions

Copy link
Copy Markdown

Some comparisons could not be completed because a pull request conflicts with the base branch. Review these shared files manually before concluding that there is no overlap.

Pull request Shared files not compared
PR 5209 core/libs/prx/libSceFont/src/Text.cpp
docs/dev/debt/libSceFont.md
PR 8250 docs/dev/debt/libSceFont.md

@MarcZX10

Copy link
Copy Markdown
Contributor

Manual follow-up to the overlap bot report at the current heads: #11521 changes CharacterStorage ownership and sceFontWritingInit in Text.cpp, and adds its lifetime debt entry. I compared #5209 (69127429), which changes FillWritingMetricsFromGlyph at a separate function and adds a separate writing-steps debt entry, and #8250 (18e0b85d), which changes Render.cpp and adds a render-surface debt entry. Neither changes the lines modified by #11521; the Text.cpp changes are separate hunks, and the debt additions are separate entries. I find no merge-order dependency on these PRs for the reviewed changes. My approval remains scoped to the reviewed behavior and its explicitly documented unverified post-destroy lifetime. This is a manual diff comparison; no additional build or title test was run.

@oneandonlydean oneandonlydean self-assigned this Oct 26, 2026
@oneandonlydean

Copy link
Copy Markdown
Collaborator

@Lindamea1 thanks for the careful analysis; the leak and the copied-writing double release on main are real. The fix moves the problem to the host, though. After sceFontDestroyString deletes the CharacterStorage, a writing still holds the raw pointer, so sceFontWritingRefersRenderStep and sceFontWritingRefersRenderStepCharacter read freed host memory, and the latter returns a writable FontTextCharacter* into it (your probe_after_destroy shows this under ASan). A guest mistake must not corrupt host memory, so this can't be left as debt.

Two designs keep your leak fix:

  1. Allocate the CharacterStorage and the characters through the string's FontMemory interface, as FontStringData already is, so a stale writing or character pointer only touches guest-freed memory; or
  2. Keep host storage but validate it: a registry of live storages (pointer plus serial) that the step exports check, returning nullptr (or throwing "not measured") once the string is destroyed.

Please add tests that step a writing after destroying its string, including a copied writing and a re-init, and check the chosen outcome; and include an ASan and leak run of guest_font.

sceFontWritingInit took a reference on the string's host character
storage and kept it in the caller's SceFontWriting bytes. Only a later
sceFontWritingInit on the same, unchanged bytes dropped it, so every
string drawn with a fresh, zeroed or overwritten writing leaked its
characters, and re-initialising both copies of a copied writing dropped
its one reference twice. A SceFontWriting has no teardown export, so it
is plain caller memory and cannot own anything.

sceFontCreateString now allocates the characters through the string's
FontMemory, as it already did the string, so no character pointer the
guest receives points into host memory. sceFontDestroyString clears
the string's magic and frees both, and a failed create clears it before
freeing the string. A writing keeps only a pointer to its string and
checks the magic on every step, so after the destroy its steps return
null unless that memory holds the magic again, as when a new string is
allocated there. An init that fails after resetting the writing still
leaves it stepping nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Lindamea1
Lindamea1 force-pushed the fix/font-writing-non-owning branch from 798a929 to ac682a4 Compare October 27, 2026 09:19
@Lindamea1

Copy link
Copy Markdown
Contributor Author

@oneandonlydean Thanks. I took your first design and pushed it as ac682a4, rebased onto main 5bc8403:

  • sceFontCreateString allocates the characters through the string's FontMemory, as it already did the string, and sceFontDestroyString frees both through it. CharacterStorage is gone, so the character pointers the guest gets point into memory from its own allocator.
  • A writing keeps only the pointer to its string and checks the string's magic before it reads the string. sceFontDestroyString clears that magic before it frees the string, as DestroyWords does (Words.cpp:275), and a failed create clears it too. So after the destroy, sceFontWritingRefersRenderStep and sceFontWritingRefersRenderStepCharacter return null on the writing and on any copy of it, unless that memory holds the string magic again, as when a new string is allocated there. With an allocator that hands out the last freed block first, such as the guest heap, that is likely when a string is created between the destroy and the step. Either way, the string and its characters come from the guest's allocator, so no host memory is freed under a writing or a character pointer.

New test, CheckWritingAfterStringDestroyed in guest_font. It gives the string its own FontMemory, whose release marks a block as released but keeps it allocated, so reads of a released block stay in memory the test owns, as reads of freed guest memory would in a title. It checks:

  • the string and its 32 characters come from that interface, and a characters allocation that fails returns SCE_FONT_ERROR_ALLOCATION_FAILED and releases the string, which a destroy through a handle to that block then rejects with SCE_FONT_ERROR_INVALID_STRING;
  • a writing stepped twice and a byte copy of it: after the destroy, the string's and the characters' blocks have been released, and on the writing and on the copy the character call returns null and sets the letter step to null, and the step call returns null;
  • re-initialising the copy with the destroyed handle returns SCE_FONT_ERROR_INVALID_STRING and leaves it stepping nothing, and a second destroy through another copy of the handle returns SCE_FONT_ERROR_INVALID_STRING and releases nothing;
  • both writings, re-initialised on a new string, step it to its end, and every block is released exactly once.

The leak check from the previous push now also requires the interface's allocation count to return to where it was after its 512 draws.

Controls, each with only Text.cpp swapped: main's aborts at line 179 (the heap check), the previous head's at line 231 (no characters come from the interface), this change without the magic clear in sceFontDestroyString at line 249 (the writing still returns its step character after the destroy), and without the clear on a failed create at line 74 (the test's release sees that block released twice).

ASan and leaks: in a -DANYPS5_ENABLE_ASAN=ON Release tree where guest_font_tests and the libraries it links were rebuilt at this head, ASAN_OPTIONS=detect_leaks=1 ctest --test-dir build-asan -R '^guest_font$' passes with no report. With main's Text.cpp and GuestFont.cpp it reports the 32- and 400-byte leaks from Text.cpp:331 and Text.cpp:345.

probe_after_destroy, the probe you cited, rebuilt against this head's ASan libraries, still reports a heap-use-after-free. It is now a 2-byte read of the destroyed string's magic in GetStringData (Text.cpp:73), in the block that the probe's own Allocate gave sceFontCreateString and its Release freed in sceFontDestroyString. The probe's FontMemory frees with free, so ASan sees that guest-allocator block. That read is the one your first design leaves, and it is why the new test keeps released blocks allocated.

The description and the debt entry are updated. The entry now says what the steps and a second destroy return here after a destroy, and that the console's results and where it allocates the characters are not measured.

@JJenkx

JJenkx commented Oct 27, 2026

Copy link
Copy Markdown
Contributor

Windows run at this PR's exact head ac682a4064 (ac682a406413a54a4cbd6e20cdc5616efaf89582), not merged onto anything else. Its parent and merge base is main 5bc84038c4.

Windows 11 Enterprise 10.0.22621, Ryzen 9 5950X, WinLibs GCC 15.2.0 UCRT r7, Ninja, Release, BUILD_TESTING=ON, in a fresh build directory.

All seven font tests pass in each of 3 runs, with no failed, skipped or not-run tests:

  • guest_font, including the new writing-ownership regressions
  • guest_font_metrics
  • guest_font_style_information
  • guest_font_outline_profile
  • guest_font_writing_line
  • guest_font_graphics
  • guest_font_words

This is an ordinary Release build. LeakSanitizer isn't available with this toolchain, so the leak itself wasn't measured on Windows. No title, console or negative control was run.

AI-assisted: yes (Claude Code).

@oneandonlydean
oneandonlydean merged commit 871517a into boykopovar:main Oct 28, 2026
11 of 12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants